package t880

import (
	"fmt"
	"strconv"
	"unicode"
)

func decodeAtIndex2(S string, K int) string {
	size := 0
	for _, c := range S {
		if unicode.IsDigit(c) {
			size *= int(c - '0')
		} else {
			size++
		}
	}
	for i := len(S) - 1; i >= 0; i-- {
		c := rune(S[i])
		K %= size
		if K == 0 && unicode.IsLetter(c) {
			return string(c)
		}
		if unicode.IsDigit(c) {
			size /= int(c - '0')
		} else {
			size--
		}
	}
	return ""
}

func decodeAtIndex(S string, K int) string {

	fmt.Println(S)
	res := ""

	sLength := 0

	// 计算展开的长度
	for _, i := range S {
		char := string(i)
		n, err := strconv.Atoi(char)
		if err != nil {
			//fmt.Println(char)
			sLength++
		} else {
			sLength += sLength * (n - 1)
		}
	}

	tmp := sLength

	for i := len(S) - 1; i >= 0; i-- {
		char := string(S[i])
		K %= tmp
		n, err := strconv.Atoi(char)
		if K == 0 && err != nil {
			res = char
			break
		}
		if err != nil {
			//fmt.Println(char)
			tmp = tmp - 1
		} else {
			tmp = tmp / n
		}

	}

	return res
}
